package com.xsh.opensltest.plugin;

import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.SeekBar;
import android.widget.TextView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.xsh.opensltest.FileUtils;
import com.xsh.opensltest.utils.FullException;

import java.io.File;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class UIParser {
    private static String tag = "UIParser";
    // 兼容旧代码
   public static View parseUI(Context context, File jsonFile) throws Exception {
       JSONObject config = new JSONObject(FileUtils.readFileToString(jsonFile));
       return buildView2(context, config.getJSONObject("root"));
   }
// 创建ui时绑定事件
    public static View parseUI(Context context, File jsonFile,Object handler) throws Exception
    {
        JSONObject config = new JSONObject(FileUtils.readFileToString(jsonFile));
        return buildView(context, config.getJSONObject("root"),handler);
    }
    // 绑定handler的动态界面创建
    private static View buildView(Context ctx, JSONObject node,Object handler) throws Exception
    {
        Log.d(tag,"开始动态创建插件界面"+node.toString());
        String type = node.getString("type");
        // 反射创建View实例
        Class<?> clazz = Class.forName("android.widget." + type);
        Constructor<?> constructor = clazz.getConstructor(Context.class);
        View view = (View) constructor.newInstance(ctx);

        // 设置基础属性
        if (node.has("text")) {
            Method setText = clazz.getMethod("setText", CharSequence.class);
            setText.invoke(view, node.getString("text"));
        }
        if(node.has("layout_width")|| node.has("layout_height") )
        {
            int width = parseDimension(ctx,node.getString("layout_width"));
            int height = parseDimension(ctx,node.getString("layout_height"));
            ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(width,height);
            view.setLayoutParams(params);
        }
        if(node.has("orientation"))
        {
            String orientation = node.getString("orientation");
            if("vertical".equals(orientation))
            {
                ((LinearLayout)view).setOrientation(LinearLayout.VERTICAL);
            }
            else if("horizontal".equals(orientation))
            {
                ((LinearLayout)view).setOrientation(LinearLayout.HORIZONTAL);
            }
        }
        if(node.has("events"))
        {
            mybind(view,node.getJSONObject("events"),handler);
        }
        if(node.has("max"))
        {
            SeekBar sb = (SeekBar)view;
            int maxValue = node.getInt("max");
            sb.post(() -> {
                try {
                    sb.setMax(maxValue);
                    Log.d(tag, "SeekBar 设置最大值 (延迟 post 成功): " + maxValue);
                } catch (Exception e) {
                    Log.e(tag, "延迟设置SeekBar max时捕获到异常: " + e.getMessage(), e);
                    FullException.print(e);
                    // 考虑在这里显示 Toast 或其他 UI 提示
                }
            });
        }
        // 递归构建子View
        if (view instanceof ViewGroup && node.has("children")) {
            JSONArray children = node.getJSONArray("children");
            for (int i = 0; i < children.length(); i++) {
                View child = buildView(ctx, children.getJSONObject(i),handler);
                ((ViewGroup) view).addView(child);
            }
        }
        return view;
    }
    /**
     *  不绑定handler的函数
     */
    private static View buildView2(Context ctx, JSONObject node) throws Exception {
        // 2025/6/4 修改为new
        String type = node.getString("type");
        View view = null;
        switch (type)
        {
            case "TextView":
                view = new TextView(ctx);
                break;
            case "SeekBar":
                view = new SeekBar(ctx);
                break;
            case "LinearLayout":
                view = new LinearLayout(ctx);
                break;
            case "RadioGroup":
                view = new RadioGroup(ctx);
                break;
            case "RadioButton":
                view = new RadioButton(ctx);
                break;
            case "CheckBox":
                view = new CheckBox(ctx);
                break;
            default:
                throw new IllegalStateException("Unexpected value: " + type);
        }

        // 设置基础属性
        if (node.has("text")) {
            ((TextView)view).setText(node.getString("text"));
            //Method setText = clazz.getMethod("setText", CharSequence.class);
            //setText.invoke(view, node.getString("text"));
        }
        if(node.has("layout_width")|| node.has("layout_height") )
        {
            int width = parseDimension(ctx,node.getString("layout_width"));
            int height = parseDimension(ctx,node.getString("layout_height"));
            //Log.d("UIParser","height"+height);
            //Log.d("UIParser","width"+width);
            ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(width,height);
            view.setLayoutParams(params);
        }
        if(node.has("orientation"))
        {
            String orientation = node.getString("orientation");
            if("vertical".equals(orientation))
            {
                ((LinearLayout)view).setOrientation(LinearLayout.VERTICAL);
            }
            else if("horizontal".equals(orientation))
            {
                ((LinearLayout)view).setOrientation(LinearLayout.HORIZONTAL);
            }
        }
        // 递归构建子View
        if (view instanceof ViewGroup && node.has("children")) {
            JSONArray children = node.getJSONArray("children");
            for (int i = 0; i < children.length(); i++) {
                View child = buildView2(ctx, children.getJSONObject(i));
                ((ViewGroup) view).addView(child);
            }
        }
        return view;
    }
    // 将尺寸字符串转换为整型值
    private static int parseDimension(Context context, String value) {
        if ("match_parent".equals(value)) {
            return ViewGroup.LayoutParams.MATCH_PARENT;
        } else if ("wrap_content".equals(value)) {
            return ViewGroup.LayoutParams.WRAP_CONTENT;
        }

        try {
            // 处理带单位的数值（如"100dp"）
            if (value.endsWith("dp")) {
                float dp = Float.parseFloat(value.substring(0, value.length() - 2));
                float density = context.getResources().getDisplayMetrics().density;
                return (int) (dp * density + 0.5f);
            }
            // 处理像素值（如"100px"）
            else if (value.endsWith("px")) {
                return Integer.parseInt(value.substring(0, value.length() - 2));
            }
            // 处理无单位的数值（默认为px）
            else {
                return Integer.parseInt(value);
            }
        } catch (NumberFormatException e) {
            return ViewGroup.LayoutParams.WRAP_CONTENT;
        }
    }
    // 重构函数明到bingEvent
    public static void mybind(View v,JSONObject events,Object handler) throws JSONException, NoSuchMethodException, InvocationTargetException, IllegalAccessException
    {
        //Log.d(tag,"事件:" + events.toString());
        //Log.d(tag ,"events.length"+ events.length());
        Iterator<String> keys = events.keys();
        while (keys.hasNext())
        {
            String eventName = keys.next();
            String paramType = events.getString(eventName);
            Log.d(tag,"EventHandler绑定，事件名称:"+ eventName);
            Log.d(tag,"EventHandler绑定，参数类型:"+ paramType);
            if(v instanceof RadioGroup)
            {
                RadioGroup radioGroup = (RadioGroup)v;
                Method method = handler.getClass().getMethod(eventName,int.class);
                radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
                    @Override
                    public void onCheckedChanged(RadioGroup group, int checkedId)
                    {
                        int selectedIndex = -1;
                        for (int i = 0; i < group.getChildCount(); i++) {
                            if (group.getChildAt(i).getId() == checkedId) {
                                selectedIndex = i;
                                break;
                            }
                        }

                        if (selectedIndex != -1) {
                            try {
                                method.invoke(handler, selectedIndex);
                            } catch (Exception e) {
                                Log.e(tag, "调用 RadioGroup 事件失败", e);
                                FullException.print(e);
                            }
                        }
                    }
                });
            }
            if(v instanceof CheckBox)
            {
                CheckBox cb = (CheckBox)v;
                Method method = handler.getClass().getMethod(eventName,boolean.class);
                cb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                    @Override
                    public void onCheckedChanged(CompoundButton compoundButton, boolean b)
                    {
                        try {
                            method.invoke(handler,b);
                        } catch (IllegalAccessException e) {
                            e.printStackTrace();
                        } catch (InvocationTargetException e) {
                            e.printStackTrace();
                        }
                    }
                });
            }
            if(v instanceof SeekBar && "int".equals(paramType))
            {
                SeekBar sb = (SeekBar)v;

                ((SeekBar) v).setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener()
                {
                    Method method;
                    @Override
                    public void onProgressChanged(SeekBar seekBar, int i, boolean b)
                    {
                        try {
                            method = handler.getClass().getMethod(eventName,int.class);
                            method.invoke(handler,i);
                        } catch (NoSuchMethodException e)
                        {
                            e.printStackTrace();
                        }
                        catch (IllegalAccessException e) {
                            FullException.print(e);
                        } catch (InvocationTargetException e) {
                            FullException.print(e);
                        }
                    }
                    @Override public void onStartTrackingTouch(SeekBar seekBar) { }@Override public void onStopTrackingTouch(SeekBar seekBar) { }
                });
            }
        }
    }
}